<?php
namespace frontend\modules\base\controllers;

use common\models\Wxuser;
use frontend\token\tokenCheck;
use yii\base\Exception;
use yii\web\Controller;

/**
 * Class BaseController
 * @package frontend\modules\base\controller
 */
class BaseController extends Controller
{
    /**
     * @var
     */
    public $post;

    public function checkAccessToken()
    {
        $userid = \Yii::$app->UserInfo->userid;
        $this->post = \Yii::$app->request->post();
        $post = $this->post;
//        $access_token = isset($post['access_token'])?$post['access_token']:'';
        $access_token = '1111';
        if($access_token&&$userid) {
            $token = new tokenCheck();
            $userinfo = $token->check($userid, $access_token);
            if($userinfo){
                return $userinfo;
            }
        } else{
            $message = ['code'=>400,'message'=>'token验证失败'];
            return json_encode($message);
        }
        $message = ['code'=>500,'message'=>'token验证失败，参数传递错误'];
        return json_encode($message);
    }

    public function setPost()
    {
        $this->post = \Yii::$app->request->post();
    }

    /**
     * @param $openId
     * @return bool
     */
    public function userSave($openId)
    {
        return true;
        /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
        $wechat = \Yii::$app->wechat;
        $menberInfo = $wechat->getMemberInfo($openId);
        if(isset($menberInfo['nickname'])){
            return true;
        }
//        $menberInfo = $this->getMenInfo($menberInfo);

        //获取用户信息，判断是否新用户，自动添加用户到数据库，页面显示已登陆状态
        $user = Wxuser::findOne(['openid'=>$menberInfo['openid']]);
        $user->wx_name = $menberInfo['nickname'];
        $user->wx_images = $menberInfo['headimgurl'];
        if($menberInfo['headimgurl']){
            $user->wx_name = $menberInfo['headimgurl'];
        }
        $user->wx_name = $menberInfo['nickname'];
        $user->username = $menberInfo['nickname'];
        $user->sex = $menberInfo['sex'];
        $user->is_gz = $menberInfo['is_gz'];
        if($user->save()) {
            return true;
        }else{
            return false;
        }
    }

    /**
     * 未关注用户数据填充
     *
     * @param $menberInfo
     * @return mixed
     */
    public function getMenInfo($menberInfo)
    {
        $menberInfo['nickname'] = isset($menberInfo['nickname'])?$menberInfo['nickname']:'小普匿名用户';
        $menberInfo['headimgurl'] = isset($menberInfo['headimgurl'])?$menberInfo['headimgurl']:\Yii::$app->params['domurl'].'wx/backend/web/images/1.png';
        $menberInfo['unionid'] = isset($menberInfo['unionid'])?$menberInfo['unionid']:'xxx';
        $menberInfo['sex'] = isset($menberInfo['sex'])?$menberInfo['sex']:1;
        $menberInfo['is_gz'] = isset($menberInfo['subscribe'])?$menberInfo['subscribe']:0;
        return $menberInfo;
    }

}